import {
  Config
} from '../utils/config.js'

import {
  Token
} from "../utils/token.js"
var token = new Token()

class Base {
  constructor() {
    this.baseUrl = Config.baseUrl
    this.tryAgain = true
  }

  updataList(res, concatOne) {
    var result = {
      data: concatOne,
      currentPage: res.current_page,
      stopMore: false
    }
    if (res.data.data) {
      result.data = concatOne.concat(res.data.data)
    } else {
      this.toast("没有更多了", "none")
      result.stopMore = true
    }
    return result
  }

  toast(title, icon) {
    if (!icon) {
      icon = 'success'
    }
    wx.showToast({
      title: title,
      icon: icon,
      duration: 2000
    })
  }

  showLoading() {
    wx.showLoading({
      title: '加载中',
    })
  }

  processRes(statusCode) {
    var firstCode = parseInt(statusCode / 100)
    if (firstCode == 2) {
      return true
    }

    return false
  }



  request(params) {
    // var that = this
    if (!params.method) {
      params.method = 'GET'
    }

    wx.request({
      url: this.baseUrl + params.url,
      method: params.method,
      data: params.data,
      header: {
        "comtent-type": "appliction/json",
        "token": wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode == 401) {
          this.tokenError(params)
        } else {
          this.tryAgain = true
          params.fn && params.fn(res)
        }
      },
      fail: function(res) {
        console.log(res)
      },
      complete: function(res) {
      }
    })
  }

  compBuyPriceFromArray(bookArray){
    bookArray.forEach((item)=>{
      var price = Number(item.discount) * Number(item.price)
      item.buyPrice = price.toFixed(1)
    })
    return bookArray
  }

  tokenError(params) {
    if (this.tryAgain) {
      this.tryAgain = false
      token.getToken(() => {
        this.request(params)
      })
    } else {
      this.toast("服务器错误，请稍后再试", "none")
    }
  }


  getBaseInfo(book, calDiscount) {
    if (calDiscount) {
      var price = Number(book.price) * Number(book.discount)
    } else {
      var price = Number(book.price) * Number(book.rate)
    }
    var item = {}
    item.price = price.toFixed(1)
    var keys = ["id", "main_img_url", "name", "isbn"]
    for (var key in book) {
      if (keys.indexOf(key) > -1) {
        item[key] = book[key]
      }
    }
    return item
  }

}

export {
  Base
}